import path from "path";
import { checkDirExists, createDirectory, writeToFile } from "../../utils/tools";

interface params {
  /**
   * 实体名
   */
  name: string;

  /**
   * 字段数组
   */
  fields: string[];

  /**
   * 上级目录
   */
  superDir: string;
}

// 创建实体类
export function generEntitiesCode({ name, fields }: params) {
  // 字段字符串
  const fieldStr = fields
    .map((item) => {
      return `
  @IsString()
  public ${item}: string;`;
    })
    .join("\n");

  // 实体类名
  const enityName = `${name}Entity`;
  // 模型名
  const modelName = `I${name}Model`;

  const tem = `import { IsString } from "class-validator";
import { BaseEntity } from "../BaseEntity";
import { Model } from "sequelize";

export default class ${enityName} extends BaseEntity {
  id?: number;
  ${fieldStr}

  public static transform(plainObject: object): ${enityName} {
    return super.baseTransform(${enityName}, plainObject);
  }
}

export interface ${modelName} extends Model<${enityName}> {}

/**
 * 导入的字段映射对象
 */
export const importFieldMap: Omit<${enityName}, "validateThis"> = {
  ${fields.map((item) => `${item}: "${item}"`)}
};
`;
  return tem;
}

export async function createEntities(param: params) {
  const codeText = generEntitiesCode(param);
  const fileName = param.name + "Entity.ts";

  // 1. 找到存放实体文件的目标目录
  const dirPath = path.resolve(__dirname, "../../entities", param.superDir);
  if (!(await checkDirExists(dirPath))) {
    await createDirectory(dirPath);
  }

  // 生成实体类文件
  const target = path.resolve(dirPath, fileName);
  await writeToFile(target, codeText);
}
